<template>
  <div>
    <el-dialog
      top="10vh"
      width="80%"
      :title="title"
      :show-close="true"
      :lock-scroll="true"
      :append-to-body="false"
      :destroy-on-close="false"
      :visible.sync="data_visible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="dialogDestroy"
    >
      <div class="main">
        <div class="upload">
          <el-upload
            ref="upload"
            class="upload-widget"
            drag
            with-credentials
            :accept="data_upload.upload_accept"
            :multiple="false"
            :show-file-list="false"
            action="no_use_string"
            :auto-upload="false"
            :file-list="data_upload.file_list"
            :on-change="uploadChange"
            :before-upload="onBeforeUpload"
            :http-request="onHttpRequest"
          >
            <template v-if="data_upload.file_list.length === 0">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
            </template>
            <template v-else>
              <i class="el-icon-document-add" />
              <div class="el-upload__text">{{ data_upload.file_list[0].name }}</div>
            </template>
            <div slot="tip" class="el-upload__tip">模板导入文件支持 .xls 或 .xlsx 文件</div>
          </el-upload>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button
          type="primary"
          :disabled="giveDialogConfirmDisableStatus()"
          @click="dialogConfirm"
        >
          <template v-if="data_upload.status === 'start' || data_upload.status === 'uploading'">上传中</template>
          <template v-else>确 定</template>
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { UploadProgressDialogService } from './upload-progress.dialog.service.js';
import { ApiMMallWeb } from '@services/api';

export default {
  name: 'UploadExcelDialogComponent',
  props: {
    title: {
      type: String,
      default: '模板导入'
    },
    query: {
      type: Object,
      default: function() {
        return {};
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    fetcher: {
      type: Function,
      default: function() {}
    },
    useProgress: {
      type: Boolean,
      default: true
    },
    useComplete: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      data_upload: {
        params: {
          orderId: this.query.orderId,
          vendorNum: this.query.vendorNum,
          productLineCode: this.query.productLineCode
        },
        status: 'free',
        // action: '/m-mall-web/api/v1/file/readFile',
        file_list: [],
        pre_file_list: [],
        upload_accept: '.xls,.xlsx'
      },
      data_visible: true,
      progress_val: 0
    };
  },
  computed: {
    apiMMallWeb: function() {
      return new ApiMMallWeb(this.fetcher);
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler: function(val, oldVal) {
        this.data_visible = val;
      }
    }
  },
  methods: {
    // 上传进度回调
    onUploadProgress(progressEvent) {
      console.log(progressEvent);
      if (progressEvent.lengthComputable) {
        let val = (progressEvent.loaded / progressEvent.total) * 100;
        val = parseInt(val, 10);
        // 这里的进度只能表明文件已经上传到后台，但是后台有没有处理完还不知道
        // 因此不能直接显示为100%，不然用户会误以为已经上传完毕，关掉浏览器的话就可能导致上传失败
        // 等响应回来时，再将进度设为100%
        if (val === 100) val = 90;
        this.progress_val = val;
        // new UploadProgressDialogService(this.fetcher)
        //   .create({
        //     query: {
        //       busId: 1,
        //       busType: 1,
        //       progress_val: this.progress_val
        //     },
        //     useComplete: this.useComplete,
        //     progressCompleteHandler: (data = {}) => {
        //       this.$emit('progressComplete', data);
        //     }
        //   })
        //   .mount();
        console.log(this.progress_val);
      }
    },
    onBeforeUpload(file, fileList) {
      let FileExt = file.name.replace(/.+\./, ''); // 名字后缀
      console.log(FileExt);
      const isLt10M = file.size / 1024 / 1024 < 10; // 文件大小
      const format = this.data_upload.upload_accept.includes(FileExt.toLowerCase());
      if (!format) {
        this.$message.error(`上传文件只支持${this.uploadAccept}类型!`);
      } else if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isLt10M && format;
    },
    onHttpRequest(data) {
      if (this.useProgress) {
        new UploadProgressDialogService(this.fetcher)
          .create({
            query: {
              busId: 1,
              busType: 1,
              progress_val: this.progress_val
            },
            useComplete: this.useComplete,
            progressCompleteHandler: (data = {}) => {
              this.$emit('progressComplete', data);
            }
          })
          .mount();
      }
      console.log(data, 'filedata');
      let fd = new FormData();
      fd.append('file', data.file);
      fd.append('productLineCode', 'BL11');
      fd.append('vendorNum', 'SBL001');
      console.log(fd);
      this.fetcher({
        method: 'post',
        url: '/m-mall-center/api/v1/file/readFile',
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: this.onUploadProgress,
        data: fd
      })
        .then(res => {
          const { code, payload, msg } = res.data;
          if (!Number(code)) {
            this.payload_data = payload;
            this.progress_val = 100;
            this.data_upload.status = 'success';
            this.$emit('complete', payload);
          } else {
            this.$message.error(msg);
          }
        })
        .catch(() => {})
        .finally(() => {});

      this.dialogDestroy();
      // let result = this.apiMMallWeb.ReadFileFileV1ApiPOST({
      //   form: fd
      // });
    },
    dialogDestroy() {
      this.$emit('destroy', false);
      this.$emit('update:visible', false);
    },
    dialogClose() {
      this.data_visible = false;
    },
    dialogConfirm() {
      this.data_upload.pre_file_list.forEach((file, index) => {
        this.$refs['upload'].abort(file);
      });
      this.data_upload.pre_file_list = this.data_upload.file_list;
      this.$refs['upload'].submit();
      this.data_upload.status = 'start';
    },
    giveDialogConfirmDisableStatus() {
      return (
        this.data_upload.status === 'start' ||
        this.data_upload.status === 'uploading' ||
        this.data_upload.file_list.length === 0
      );
    },
    // uploadError(error, file, fileList) {
    //   this.data_upload.status = 'error';
    //   this.$message.error('上传失败');
    // },
    // uploadRemove(file, fileList) {
    //   if (fileList.length > 0) {
    //     this.data_upload.status = 'ready';
    //   } else {
    //     this.data_upload.status = 'free';
    //   }
    //   this.data_upload.file_list = fileList;
    // },
    uploadChange(file, fileList) {
      if (fileList.length > 0) {
        this.data_upload.status = 'ready';
        this.data_upload.file_list = fileList.slice(-1);
      } else {
        this.data_upload.status = 'free';
        this.data_upload.file_list = fileList;
      }
    }
    // uploadSuccess(response, file, fileList) {
    //   console.log('success');
    //   this.data_upload.status = 'success';
    //   if (response) {
    //     this.$refs['upload'].clearFiles();
    //     // this.data_visible = false;
    //     this.$emit('complete', fileList);
    //   }
    // },
    // uploadProgress(event, file, fileList) {
    //   console.log('uploadProgress');
    //   this.data_upload.status = 'uploading';
    // }
  }
};
</script>

<style lang="less" scoped>
.upload {
  width: 360px;
  margin: 0 auto;

  .upload-widget {
    .el-icon-document-add {
      font-size: 67px;
      color: #a7b1c7;
      margin: 40px 0 16px;
      line-height: 50px;
    }

    .el-upload__text {
      padding: 0 20px;
    }

    .el-upload__tip {
      color: #999;
      text-align: center;
    }
  }
}

.dialog-footer {
  text-align: center;
}
</style>
